/*
 * =====================================================================================
 *
 *       Filename:  sdlstuff.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  22.01.2010 12:09:23
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Michal Antonczak (uzyszkodnik), uzyszkodnik.priv@gmail.com
 *        Company:  
 *
 * =====================================================================================
 */

#include 	"sdlstuff.h"
#include	<SDL/SDL.h>
#include	<SDL/SDL_image.h>

using namespace std;

void putpixel(SDL_Surface *surf,int x, int y, Uint8 R, Uint8 G, Uint8 B){

    Uint32 pixel= SDL_MapRGB(surf->format, R, G, B);

    int bpp = surf->format->BytesPerPixel;

    /* Obliczamy adres pixela */
    Uint8 *p = (Uint8 *)surf->pixels + y * surf->pitch + x * bpp;

    switch(bpp)
    {
        case 1: //8-bit
            *p = pixel;
            break;

        case 2: //16-bit
            *(Uint16 *)p = pixel;
            break;

        case 3: //24-bit
            if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
                p[0] = (pixel >> 16) & 0xff;
                p[1] = (pixel >> 8) & 0xff;
                p[2] = pixel & 0xff;
            } else {
                p[0] = pixel & 0xff;
                p[1] = (pixel >> 8) & 0xff;
                p[2] = (pixel >> 16) & 0xff;
            }
            break;

        case 4: //32-bit
            *(Uint32 *)p = pixel;
            break;
    }


}

void sdlerror(char* str){
	printf("%s: %s", str,SDL_GetError());
	exit(1);
	

}
SDL_Surface* load_img(string filename){

	SDL_Surface* l_img=NULL;
	SDL_Surface* optimizedimg = NULL;

	if((l_img = IMG_Load(filename.c_str()))==NULL)
		sdlimgerror("loading img");
	
	if((optimizedimg = SDL_DisplayFormat(l_img))==NULL)
		sdlerror("img conversion");
	SDL_FreeSurface(l_img);

	/*
	Uint32 colorkey = SDL_MapRGB( optimizedimg->format, 0,0xFF, 0xFF);
	SDL_SetColorKey(optimizedimg, SDL_SRCCOLORKEY, colorkey);
	*/

	return optimizedimg;


}


/*
void sdlquit(){
	SDL_Quit();
	IMG_Quit();
}
*/

void sdlimgerror(char* str){
	printf("%s: %s",str, IMG_GetError());
	exit(1);
}
